package com.patrol.logisticsmanage.ui.todo;

import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.patrol.logisticsmanage.R;
import com.patrol.logisticsmanage.net.BaseObserver;
import com.patrol.logisticsmanage.net.BaseReponse;
import com.patrol.logisticsmanage.net.BaseRequest;
import com.patrol.logisticsmanage.net.TodoInfo;
import com.patrol.logisticsmanage.ui.appear.ExpandableGridView;
import com.patrol.logisticsmanage.ui.appear.ImageAdapter;
import com.patrol.logisticsmanage.ui.appear.ImageInfo;
import com.patrol.logisticsmanage.ui.appear.model.City;
import com.patrol.logisticsmanage.ui.appear.model.CompleteInputInfo;
import com.patrol.logisticsmanage.ui.appear.model.EvaluateInputInfo;
import com.patrol.logisticsmanage.ui.appear.model.Province;
import com.patrol.logisticsmanage.ui.appear.model.ServiceOrder;
import com.patrol.logisticsmanage.ui.base.BaseActivity;
import com.patrol.logisticsmanage.ui.base.DialogHelper;
import com.patrol.logisticsmanage.ui.base.ImagePreviewUtils;
import com.patrol.logisticsmanage.ui.base.PickerDialog;
import com.patrol.logisticsmanage.ui.canteen.utils.GsonUtil;
import com.patrol.logisticsmanage.ui.canteen.utils.ToastUtils;

import org.jaaksi.pickerview.dataset.OptionDataSet;
import org.jaaksi.pickerview.dialog.OnPickerChooseListener;
import org.jaaksi.pickerview.picker.BasePicker;
import org.jaaksi.pickerview.picker.OptionPicker;
import org.jaaksi.pickerview.util.Util;
import org.jaaksi.pickerview.widget.DefaultCenterDecoration;
import org.jaaksi.pickerview.widget.PickerView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

@Route(path = "/app/MyAppearDetailActivity")
public class MyAppearDetailActivity extends BaseActivity implements OptionPicker.OnOptionSelectListener {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_todo_time)
    TextView tvTodoTime;
    @BindView(R.id.tv_create_time)
    TextView tvCreateTime;
    @BindView(R.id.tv_assign_time)
    TextView tvAssignTime;
    @BindView(R.id.tv_finish_time)
    TextView tvFinishTime;
    @BindView(R.id.tv_todo_address)
    TextView tvTodoAddress;
    @BindView(R.id.tv_todo_content)
    TextView tvTodoContent;
    @BindView(R.id.grid_exp)
    ExpandableGridView gridExp;
    @BindView(R.id.tv_todo_status)
    TextView tvTodoStatus;

    ImageAdapter adapter;
    List<ImageInfo> imageInfos;
    @BindView(R.id.rg_consumable)
    RadioGroup rgConsumable;
    @BindView(R.id.tv_add_consumable)
    TextView tvAddConsumable;
    @BindView(R.id.table_layout)
    TableLayout tableLayout;
    @BindView(R.id.ll_show)
    LinearLayout llShow;
    @BindView(R.id.tv_done)
    TextView tvDone;
    @BindView(R.id.ll_do)
    LinearLayout llDo;
    @BindView(R.id.tv_cancel)
    TextView tvCancel;

    @Autowired
    String order;
    ServiceOrder serviceOrder;
    boolean isComplete = false;
    @BindView(R.id.img_status)
    ImageView imgStatus;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_appear_detail);
        ButterKnife.bind(this);
        serviceOrder = GsonUtil.gsonToBean(order, ServiceOrder.class);
        tvTitle.setText("我的报修订单");
        initPickerView();
        initViews();


    }

    private void initViews() {
        imageInfos = new ArrayList<>();
        adapter = new ImageAdapter(imageInfos, this, new ImageAdapter.OnItemDeleteClick() {
            @Override
            public void onItemDeleteClick(int position) {

            }
        }, new ImageAdapter.OnItemClick() {
            @Override
            public void onItemClick(int position) {
                ImagePreviewUtils.goToPreview(imageInfos, position, MyAppearDetailActivity.this);
            }
        });
        adapter.setShowDelete(false);
        gridExp.setAdapter(adapter);

        tableLayout.setColumnStretchable(0, true);
        addRow();

        rgConsumable.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb_need) {
                    llShow.setVisibility(View.VISIBLE);
                } else if (checkedId == R.id.rb_unneed) {
                    llShow.setVisibility(View.GONE);
                }
            }
        });

        tvTodoTime.setText(serviceOrder.shangmsd);
        tvCreateTime.setText(serviceOrder.createTime);
        tvAssignTime.setText(serviceOrder.assignTime);
        tvFinishTime.setText(serviceOrder.finishTime);
        tvTodoAddress.setText(serviceOrder.yingqId_dictText + " " + serviceOrder.louy_dictText + " " + serviceOrder.floor + "层" + serviceOrder.room);
        tvTodoStatus.setText(serviceOrder.weixzt_dictText);
        tvTodoContent.setText(serviceOrder.problem);
        imageInfos.addAll(getImageInfos(serviceOrder.picture));
        adapter.notifyDataSetChanged();

        if (TextUtils.equals(serviceOrder.weixzt, "2")) {
            tvDone.setText("完成");
        } else if (TextUtils.equals(serviceOrder.weixzt, "3")) {
            tvDone.setText("评价");
        } else {
            tvDone.setVisibility(View.GONE);
        }

    }

    private void addRow() {
        TableRow row = (TableRow) LayoutInflater.from(this).inflate(R.layout.item_row, tableLayout, false);
        TextView textView = row.findViewById(R.id.tv_choose);
        EditText editText = row.findViewById(R.id.et_input_number);
        setConfrim(textView);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPicker.show();
            }
        });
        tableLayout.addView(row);
        tableLayout.requestLayout();
    }

    @OnClick({R.id.tv_add_consumable, R.id.tv_done, R.id.tv_cancel})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_add_consumable:
                addRow();
                break;
            case R.id.tv_done:
                if (TextUtils.equals(serviceOrder.weixzt, "2") && !isComplete) {
                    isComplete = true;
                    tvDone.setText("确定");
                    tvCancel.setVisibility(View.VISIBLE);
                    rgConsumable.setVisibility(View.VISIBLE);
                } else if (TextUtils.equals(serviceOrder.weixzt, "2") && isComplete) {
                    DialogHelper.showTwoChoiceDialog(mContext, "完成订单", "确认完成该订单？", "取消", "确认", new DialogHelper.DialogListenerEmpty() {
                        @Override
                        public void handleMessage() {

                        }
                    }, new DialogHelper.DialogListenerEmpty() {
                        @Override
                        public void handleMessage() {
                            armature();
                        }
                    });
                } else if (TextUtils.equals(serviceOrder.weixzt, "3")) {
                    DialogHelper.showEditDialog(mContext, "请输入您对该服务的评价内容", new DialogHelper.DialogListenerContent() {
                        @Override
                        public void handleMessage(String... content) {
                            if (TextUtils.isEmpty(content[0])) {
                                ToastUtils.showToast("请输入评价内容");
                            } else {
                                evaluate(content[0]);
                            }
                        }
                    });
                }

                break;
            case R.id.tv_cancel:
                tvCancel.setVisibility(View.GONE);
                tvDone.setText("完成");
                isComplete = false;
                break;
        }
    }

    private void evaluate(String content) {
        EvaluateInputInfo evaluateInputInfo = new EvaluateInputInfo()
                .setId(serviceOrder.id)
                .setAuditMemo(content)
                .setAuditStatus("1")
                .setProcessInstanceId(serviceOrder.processInstanceId)
                .setTaskId(serviceOrder.taskId);
        BaseRequest.getInstance().getApiServise().evaluate(evaluateInputInfo)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<Map>(mContext) {
                    @Override
                    public void onSuccess(BaseReponse<Map> baseReponse) {
                        ToastUtils.showToast("评价成功，感谢您的反馈");
                        tvDone.setVisibility(View.GONE);
                    }

                    @Override
                    public void onCodeError(BaseReponse tBaseReponse) {
                    }

                    @Override
                    public void onFailure(Throwable e, boolean netWork) throws Exception {
                    }
                });
    }

    private void complete(String content) {
        CompleteInputInfo completeInputInfo = new CompleteInputInfo()
                .setId(serviceOrder.id)
                .setAuditMemo(content)
                .setAuditStatus(1)
                .setProcessInstanceId(serviceOrder.processInstanceId)
                .setTaskId(serviceOrder.taskId);
        BaseRequest.getInstance().getApiServise().complete(completeInputInfo)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<Map>(mContext) {
                    @Override
                    public void onSuccess(BaseReponse<Map> baseReponse) {
                        ToastUtils.showToast("维修完成");
                        finish();
                    }

                    @Override
                    public void onCodeError(BaseReponse tBaseReponse) {
                    }

                    @Override
                    public void onFailure(Throwable e, boolean netWork) throws Exception {
                    }
                });
    }

    private void armature() {
        List<ArmatureInfo> armatureInfos = new ArrayList<>();
        armatureInfos.add(new ArmatureInfo()
                .setCode("ktzz001").setName("空调转子").setShul("1").setRemarks(""));
        TodoInfo todoInfo = new TodoInfo()
                .setId(serviceOrder.id)
                .setHqYfRepairPieceList(armatureInfos);
        BaseRequest.getInstance().getApiServise().editArmature(todoInfo)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<Map>(mContext) {
                    @Override
                    public void onSuccess(BaseReponse<Map> baseReponse) {
                        complete("修完了，客户很满意");
                    }

                    @Override
                    public void onCodeError(BaseReponse tBaseReponse) {
                    }

                    @Override
                    public void onFailure(Throwable e, boolean netWork) throws Exception {
                    }
                });
    }

    //配件选择器
    private OptionPicker mPicker;
    DefaultCenterDecoration decoration;
    PickerDialog pickerDialog;
    Dialog dialog;

    private void initPickerView() {
        // 设置CenterDecoration
        decoration = new DefaultCenterDecoration(mContext);
        decoration
                .setLineColor(Color.parseColor("#dd199475"))
//                .setDrawable(Color.parseColor("#199475"))
                //.setDrawable(Color.parseColor("#999999"))
                .setLineWidth(1)
                .setMargin(Util.dip2px(mContext, 10), Util.dip2px(mContext, -3), Util.dip2px(mContext, 10),
                        Util.dip2px(mContext, -3));
        mPicker =
                new OptionPicker.Builder(mContext, 2, this)
                        .dialog(new PickerDialog())
                        .setInterceptor(new BasePicker.Interceptor() {
                            @Override
                            public void intercept(PickerView pickerView, LinearLayout.LayoutParams params) {
                                int level = (int) pickerView.getTag();
                                pickerView.setVisibleItemCount(3);
                                // setInterceptor 可以根据level区分设置pickerview属性
                                pickerView.setCenterDecoration(decoration);
                                pickerView.setTextSize(15, 20);
                                pickerView.setColor(Color.parseColor("#199475"), Color.parseColor("#444444"));
                            }
                        }).create();
        pickerDialog = (PickerDialog) mPicker.dialog();
        dialog = pickerDialog.getDialog();

        //DefaultPickerDialog dialog = (DefaultPickerDialog) mPicker.dialog();
        pickerDialog.getTitleView().setText("请选择配件");
        // 设置弹窗
        dialog.setCanceledOnTouchOutside(true);
        dialog.getWindow().setGravity(Gravity.BOTTOM);
        data = createData();
        mPicker.setData(data);
    }

    private void setConfrim(TextView textView) {
        // 拦截缺点按钮的事件
        pickerDialog.setOnPickerChooseListener(new OnPickerChooseListener() {
            @Override
            public boolean onConfirm() {
                Province province = data.get(mPicker.getSelectedPosition()[0]);
                City city = province.citys.get(mPicker.getSelectedPosition()[1]);
                textView.setText(province.name + " " + city.name);
                dialog.dismiss();
                // 返回false表示拦截
                return false;
            }

            @Override
            public void onCancel() {
            }
        });
    }

    List<Province> data;

    private List<Province> createData() {
        List<Province> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Province province = new Province();
            province.id = 100 * i;
            province.name = "种类" + i;
            province.citys = new ArrayList<>();
            for (int j = 0; j < (i == 1 ? 1 : 10); j++) {
                City city = new City();
                city.id = province.id + 10 * j;
                city.name = i + "-样式" + j;
                city.counties = new ArrayList<>();
                province.citys.add(city);
            }
            list.add(province);
        }
        return list;
    }

    @Override
    public void onOptionSelect(OptionPicker picker, int[] selectedPosition, OptionDataSet[] selectedOptions) {

    }

    private List<ImageInfo> getImageInfos(String images) {
        List<ImageInfo> imageInfos = new ArrayList<>();
        images = images + ",";
        while (images.contains(",")) {
            int loc = images.indexOf(",");
            imageInfos.add(new ImageInfo().setImageUrl(images.substring(0, loc)));
            images = images.substring(loc + 1);
        }
        return imageInfos;
    }
}
